<?php


namespace app\model;


use Exception;
use think\facade\Db;
use think\response\Json;

class ConfigModel
{
    private static $_baseTable = 'eb_config'; // 配置表

    /**
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [1]);
            if ($rtn instanceof Json) return $rtn;
            // 获取列表
            $table = Db::table(self::$_baseTable);
            $table->field('id, name, value, describe');
            $map = [];
            if ($input['name'] !== '') $map[] = ['name', 'like', "%{$input['name']}%"];
            $table->where($map);
            $count = $table->count();
            if ($count == 0 ) return jsonSuccess('查询成功', ['count'=> $count, 'list' => []]);
            $list = $table->order('id', 'desc')->page($input['page'], $input['limit'])->select();
            return jsonSuccess('查询成功', ['count'=> $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 获取单个信息
     * @param $input
     * @param $token
     * @return Json
     */
    public static function only($input, $token)
    {
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [1]);
            if ($rtn instanceof Json) return $rtn;
            // 获取单个信息
            $map[] = ['id', '=', $input['id']];
            $rtn = Db::table(self::$_baseTable)->field('id,value,describe,name')->where($map)->find();
            if ($rtn) return jsonSuccess('获取成功', $rtn);
            return jsonFail('未找到信息');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 编辑配置
     * @param $input
     * @param $token
     * @return Json
     */
    public static function edit($input, $token)
    {
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [1]);
            if ($rtn instanceof Json) return $rtn;
            // 编辑配置
            $map[] = ['id', '=', $input['id']];
            unset($input['id']);
            $rtn = Db::table(self::$_baseTable)->where($map)->update($input);
            if ($rtn == 1) {
                return jsonSuccess('编辑成功');
            }
            return jsonFail('编辑失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}